package com.hunit.mqtt_dome.config;

import com.hunit.mqtt_dome.emqx.MqttAcceptClient;
import com.hunit.mqtt_dome.emqx.MqttSendClient;
import com.hunit.mqtt_dome.properties.MqttProperties;
import com.hunit.mqtt_dome.service.MqttMessageReceiveService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.annotation.Conditional;
import org.springframework.context.annotation.Configuration;

/**
 * @Description : MQTT配置类
 * @Author : Sherlock
 * @Date : 2023/8/1 16:35
 */
@Configuration
@Conditional(MqttCondition.class)
public class MqttConfig implements ApplicationRunner {

    private static final Logger logger = LoggerFactory.getLogger(MqttConfig.class);

    @Autowired
    private MqttProperties mqttProperties;

    @Autowired
    private MqttAcceptClient mqttAcceptClient;

    @Autowired
    private MqttSendClient mqttSendClient;
    
    @Autowired
    private MqttMessageReceiveService mqttMessageReceiveService;

    /**
     * 启动成功后连接MQTT服务器
     *
     * @param args 启动参数
     */
    @Override
    public void run(ApplicationArguments args) {
        if (mqttProperties.getIsOpen()) {
            logger.info("开始初始化MQTT客户端...");
            
            // 启动接收客户端
            boolean acceptConnected = mqttAcceptClient.connect();
            if (acceptConnected) {
                logger.info("MQTT接收客户端连接成功");
                // 使用服务接口订阅默认主题
                boolean subscribed = mqttMessageReceiveService.subscribe(mqttProperties.getDefaultTopic(), mqttProperties.getQos());
                if (subscribed) {
                    logger.info("默认主题 {} 订阅成功", mqttProperties.getDefaultTopic());
                } else {
                    logger.error("默认主题 {} 订阅失败", mqttProperties.getDefaultTopic());
                }
            } else {
                logger.error("MQTT接收客户端连接失败，无法订阅主题");
            }
            
            // 初始化发送客户端并连接
            boolean sendConnected = mqttSendClient.connect();
            if (sendConnected) {
                logger.info("MQTT发送客户端连接成功");
            } else {
                logger.error("MQTT发送客户端连接失败");
            }
            
            logger.info("MQTT客户端初始化完成");
        } else {
            logger.info("MQTT功能未启用，跳过MQTT客户端初始化");
        }
    }
} 